package com.yunxin.mybatisplus.utils.datahandler;

/**
 * ClassName: ResponseUtil
 * Package: com.yunxin.shcommon
 * Description:
 *
 * @Author sbx
 * @Create 2025/5/16 13:48
 */

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * description: 响应工具类（这个工具类中的所有方法都会让统一处理返回数据失效，包含自定义注解@DataProcess）
 *
 * @author sbx
 * @create 2024/8/6 10:30
 */
public class ResponseUtil {

    // 添加: 创建静态的ObjectMapper实例，避免重复创建
    private static final ObjectMapper mapper = new ObjectMapper();

    /**
     * description: 将统一返回的封装类写入响应体中
     *
     * @param response
     * @param httpResult
     * @return void
     * @author sbx
     * @create 2024/8/6 10:31
     */
    public static void out(HttpServletResponse response, HttpResult httpResult) {
        response.setStatus(HttpStatus.OK.value());
        response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        try {
            mapper.writeValue(response.getWriter(), httpResult);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * description: 将任意对象转为JsonNode
     *
     * @param data
     */
    public static <T> JsonNode jsonNode(T data) {
        return mapper.valueToTree(data);
    }

    /**
     * description: 将任意对象转为HttpResult
     *
     * @param data
     */
    public static <T> HttpResult out(T data) {
        return HttpResult.success(mapper.valueToTree(data));
    }
}


